<template>
  <div class="my-page-layout">
    <div class="my-page-header">
      <div class="my-page-addProject" @click="handleOpenPageDialog">
        <img :src="newProject" alt="">
        <div>创建页面</div>
      </div>
      <div class="page-go-home">
        <el-tooltip class="toolTipHover" effect="dark" content="返回项目" placement="bottom" trigger="hover">
          <span class="iconfont icon-fanhui" @click="handlePageBack"></span>
        </el-tooltip>
      </div>
    </div>
    <div class="my-list-header">
      <div class="my-list-header_title">
        {{ projectInfo.name }}
      </div>
      <div class="my-list-header_mange flex_common">
        <el-input size="small" placeholder="搜索" v-model="query.name" @keyup.enter.native="getPageList" clearable
                  @change="getPageList"></el-input>
      </div>
    </div>
    <el-row :gutter="10" v-loading="pageLoading">
      <el-col :xs="24" :sm="4" :md="4" :lg="4" :xl="4" v-for="page in pageList">
        <dv-border-box7 class="my-list" :key="page.project_id">
          <div class="my-list_content">
            <div class="my-list-body">
              <div class="my-list-body-img">
                <img :src="page.thumb" alt="">
                <div class="my-list-body-edit">
                  <div class="my-list-body-edit-btn">
                    <div>
                      <router-link
                          :to="{ name: 'Design', params: { id: page.page_url,} }"
                          target="_blank"
                          class="edit-wrap"
                      >
                        <el-button size="small" class="btn_edit cursor_point">页面设计</el-button>
                      </router-link>
                    </div>
                    <div class="btn_edit_icon">
                      <el-tooltip class="toolTipHover" effect="dark" content="复制页面" placement="bottom" trigger="hover">
                        <i class="iconfont icon-copy_link cursor_point" :key="page.page_id"
                           @click="handleCopyPage(page.page_id)"/>
                      </el-tooltip>
                      <el-tooltip class="toolTipHover" effect="dark" content="导出页面" placement="bottom" trigger="hover">
                        <i class="iconfont icon-export cursor_point" :key="page.page_id"
                           @click="handleExportPage(page)"></i>
                      </el-tooltip>
                      <el-tooltip class="toolTipHover" effect="dark" content="复制页面链接" placement="bottom"
                                  trigger="hover">
                        <i class="iconfont icon-copy_link cursor_point" :key="page.page_id"
                           @click="handleCopyUrl"></i>
                      </el-tooltip>
                      <el-tooltip class="toolTipHover" effect="dark" content="删除页面" placement="bottom" trigger="hover">
                        <i class="iconfont icon-delete cursor_point" :key="page.page_id"
                           @click="handleDelPage(page.page_id)"></i>
                      </el-tooltip>
                    </div>
                  </div>
                  <div class="my-list-body-edit-icon">
                    <el-tooltip class="toolTipHover" effect="dark" content="发布页面" placement="bottom" trigger="hover">
                      <i class="iconfont icon-publish cursor_point" :key="page.page_id"
                         @click="handlePublish(page.page_id)"></i>
                    </el-tooltip>
                    <el-tooltip class="toolTipHover" effect="dark" content="预览页面" placement="bottom" trigger="hover">
                      <i class="iconfont icon-preview cursor_point" :key="page.page_id"
                         @click="handlePreview(page.page_url)"></i>
                    </el-tooltip>
                  </div>
                </div>
              </div>
            </div>
            <div class="my-list-footer">
              <div v-if="editFlag && selectId===page.page_id">
                <el-input v-model="page.name" @blur="handleEditPageName" size="small" placeholder="输入名称"
                          @keydown.enter="$event.target.blur()"></el-input>
              </div>
              <div v-else>
                {{ page.name }}
                <span class="iconfont icon-edit edit-btn" @click="editPageName(page)"></span>
              </div>
              <div v-if="page.publish === 1">
                <span class="dotted publish"></span>已发布
              </div>
              <div v-else>
                <span class="dotted no-publish"></span>未发布
              </div>
            </div>
          </div>
        </dv-border-box7>
      </el-col>
    </el-row>
    <el-drawer
        v-model="drawerActive"
        title="新增专案"
        size="24%"
        direction="rtl">
      <el-form
          :model="pageModel"
          :rules="rules"
          ref="pageFormRef"
          label-placement="left"
          label-align="right"
          :label-width="80"
          size="small">
        <el-form-item label="页面名称:" prop="name">
          <el-input placeholder="页面名称" v-model="pageModel.name"/>
        </el-form-item>
        <el-form-item label="备注:" prop="remark">
          <el-input placeholder="备注"
                    v-model="pageModel.remark"
                    type="textarea"
                    :autosize="{
                          minRows: 3,
                          maxRows: 5
                        }"/>
        </el-form-item>
        <el-upload
            class="avatar-uploader"
            :action="requestUrl" :headers="{Authorization:token}"
            :show-file-list="false"
            :on-success="handlePicUploadFinish"
            @before-upload="beforePicUpload">
          <img v-if="pageModel.thumb" :src="pageModel.thumb" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <span class="iconfont icon-Add"></span>
          </el-icon>
        </el-upload>
      </el-form>
      <div class="footer-modal">
        <el-button type="primary" size="small" class="base-primary-btn m_lr_10" @click="handleAddPageAction">确认
        </el-button>
        <el-button size="small" @click="drawerActive = false">取消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { defineComponent, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { addPage, deletePage, editPage, getPageInfoByProjectId, publishPage } from "../../service/project";
import DvBorderBox7 from "./../../components/datav/border-box7/src/main.vue";
import newProject from "../../assets/png/new-project.png";
import { getToken } from "../../utils/storage";
import { pageCopyById, readPageInfo } from "../../service/page";
import { saveJSON } from "../../utils/utils";
import { ElMessage, ElMessageBox } from "element-plus";

export default defineComponent({
  name: "my-page-list",
  components: {
    DvBorderBox7,
  },
  setup() {
    const query = ref({
      name: "",
      project_id: ""
    });
    const router = useRouter();
    const route = useRoute();
    const projectInfo = ref({
      name: ""
    });
    const pageModel = ref({
      name: "",
      thumb: "",
      remark: "",
      project_id: ""
    });
    const pageFormRef = ref(null);
    const pageLoading = ref(false);
    const formLoading = ref(false);
    const editFlag = ref(false);
    const selectId = ref(null);
    const pageList = ref([]);
    const drawerActive = ref(false);
    const requestUrl = ref();
    const token = ref("");
    const requestData = ref("");
    const resetForm = () => {
      pageModel.value = {
        thumb: "",
        name: "",
        project_id: route.query.project_id,
        remark: ""
      };
    };
    watch(() => route.query, (newV, preV) => {
      if (newV.project_id) {
        getPageList(newV.project_id);
      } else {
        handlePageBack();
      }
    });
    const handlePageBack = () => {
      if (route.path.includes("project/page")) {
        router.replace({ path: "list" });
      }
    };
    const getPageList = () => {
      query.value.project_id = route.query.project_id;
      pageLoading.value = true;
      getPageInfoByProjectId(query.value).then(res => {
        projectInfo.value = res.data.projectInfo;
        pageList.value = res.data.pageList;
        pageLoading.value = false;
      }).catch(err => {
        ElMessage.error(err.message);
        pageLoading.value = false;
      });
    };
    const handleDelPage = (page_id) => {
      ElMessageBox.confirm(
          "你确定删除当前页面?",
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
      ).then(() => {
        pageLoading.value = true;
        deletePage({ page_id }).then(() => {
          ElMessage({
            message: "删除页面成功",
            type: "success",
          });
          getPageList();
        }).catch(err => {
          ElMessage.error(err.message);
          pageLoading.value = false;
        });
      });
    };
    const handlePublish = (page_id) => {
      ElMessageBox.confirm(
          "你确定发布当前页面",
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
      ).then(() => {
        pageLoading.value = true;
        publishPage({ page_id }).then(() => {
          ElMessage({
            message: "发布页面成功",
            type: "success",
          });
          getPageList();
        }).catch(err => {
          ElMessage.error(err.message);
          pageLoading.value = false;
        });
      });
    };
    const editPageName = (page) => {
      pageModel.value = page;
      selectId.value = page.page_id;
      editFlag.value = true;
    };
    const handleEditPageName = () => {
      if (!page.value.thumb) {
        ElMessage.error("请输入页面名称");
        return;
      }
      pageLoading.value = true;
      editPage(pageModel.value).then(res => {
        ElMessage({
          message: "修改页面成功",
          type: "success",
        });
        getPageList();
        drawerActive.value = false;
        editFlag.value = false;
      }).catch(err => {
        ElMessage.error(err.message);
        pageLoading.value = false;
      });
    };
    const handleOpenPageDialog = () => {
      resetForm();
      drawerActive.value = true;
    };
    const handleAddPageAction = () => {
      formLoading.value = true;
      pageFormRef.value.validate((valid) => {
        if (valid) {
          addPage(pageModel.value).then(res => {
            ElMessage({
              message: "新增页面成功",
              type: "success",
            });
            getPageList();
            drawerActive.value = false;
            formLoading.value = false;
          }).catch(err => {
            ElMessage.error(err.message);
            formLoading.value = false;
          });
        }
      });
    };
    const handlePicUploadFinish = ({ file, event }) => {
      const res = JSON.parse(event.target.response);
      if (res.code === 0) {
        const { result, path } = res.data;
        pageModel.value.thumb = import.meta.env.VITE_APP_REQUEST + path;
        requestData.value = import.meta.env.VITE_APP_REQUEST + path;
      }
    };
    const beforePicUpload = ({ file, fileList }) => {
      if (fileList.length >= 1) {
        ElMessage.error("只能上传一个文件,如果已有上传文件,请删除!");
        return false;
      }
      if (!["image/jpeg", "image/png", "image/jpg"].includes(file.file.type)) {
        ElMessage.error("只能上传png/jpg格式的文件，请重新上传");
        return false;
      }
      return true;
    };
    const handlePreview = (id) => {
      let routeData = router.resolve({
        name: "Preview",
        params: { screenId: id, }
      });
      window.open(routeData.href, "_blank");
    };
    const handleCopyUrl = (page_url) => {
    };
    const handleCopyPage = (page_id) => {
      pageLoading.value = false;
      pageCopyById({ page_id }).then(res => {
        ElMessage({
          message: "页面拷贝成功",
          type: "success",
        });
        getPageList();
      }).catch(() => {
        pageLoading.value = false;
      });
    };
    const handleExportPage = (page) => {
      pageLoading.value = true;
      readPageInfo({ page_url: page.page_url }).then(res => {
        saveJSON(res.data.result, `${page.name}.json`);
        pageLoading.value = false;
      }).catch(() => {
        pageLoading.value = false;
      });
    };
    onMounted(() => {
      token.value = "Bearer " + getToken();
      requestUrl.value = import.meta.env.VITE_APP_REQUEST + "/v1/dataPicture/upload";
      getPageList();
    });
    return {
      handlePageBack,
      getPageList,
      handleDelPage,
      handlePublish,
      handlePreview,
      handleCopyUrl,
      handleCopyPage,
      handleExportPage,
      pageLoading,
      formLoading,
      token,
      requestUrl,
      projectInfo,
      pageList,
      query,
      editFlag,
      selectId,
      pageModel,
      pageFormRef,
      requestData,
      handlePicUploadFinish,
      beforePicUpload,
      editPageName,
      handleEditPageName,
      newProject,
      drawerActive,
      handleOpenPageDialog,
      handleAddPageAction,
      rules: ref({
        name: {
          required: true,
          trigger: ["blur", "input"],
          message: "请输入专案名称"
        }
      }),
    };
  }
});
</script>

<style lang="less" scoped>
@import "../../style/page/my-page.less";

.flex_common {
  display: flex;
  aligel-items: center;
}

.upload-csv {
  font-size: 44px;
}
</style>
